<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        #box{
            width: 100px;height: 100px;background: pink;position: absolute;left: 0;top: 0;
        }

    </style>
</head>
<body>
    <div id="box"></div>
</body>
<script>
    class Drag{
        constructor(){
            this.box=document.getElementById("box");
            this.init();
            this.addEvent();
        }
        init(){
            const obj = localStorage.getItem("obj") ? JSON.parse(localStorage.getItem("obj")) : {};
            this.box.style.left = obj.left + "px";
            this.box.style.top = obj.top + "px";
        }
        addEvent(){
            const that = this;
            this.box.onmousedown = function(eve){
                that.downE = eve || window.event;
                that.down();
            }
        }
        down(){
            const that = this;
            document.onmousemove = function(eve){
                that.moveE = eve || window.event;
                that.move();
            }
            document.onmouseup = function(){
                that.up();
            }
        }
        move(){
            let l=this.moveE.pageX - this.downE.offsetX ;
            let t=this.moveE.pageY - this.downE.offsetY ;
            if(l<0) l=0;
            if(t<0) t=0;
            const clientW=document.documentElement.clientWidth
            const clientH=document.documentElement.clientHeight;
            if(l > clientW - box.offsetWidth) l = clientW - box.offsetWidth;
            if(t > clientH - box.offsetHeight) t = clientH - box.offsetHeight;
            this.box.style.left = l+"px";
            this.box.style.top = t+"px";
        }
        up(){
            document.onmousemove=document.onmouseup=null;
            const obj = {
                left:this.box.offsetLeft,
                top:this.box.offsetTop
            }

            localStorage.setItem("obj", JSON.stringify(obj));
        }
    }

    new Drag();
</script>
</html>